<template>
  <div>
    <Row>
      <Col span="5">
        <Card>
          <p slot="title">
            <Icon type="ios-list-outline"></Icon>
            菜单列表
          </p>
          <div slot="extra">
            <a href="#" @click.prevent="handleAdd">
              <Icon type="plus-round" size="18"></Icon>
            </a>
            <a href="#" @click.prevent="handleDelete()" style="padding-left: 10px">
              <Icon type="trash-b" size="18"></Icon>
            </a>
          </div>
          <div>
            <Input v-model.trim="searchText" icon="search" placeholder="菜单名称" @on-change="handleSearch"></Input>
            <menu-tree
              :menuList="menuTreeList"
              @menuIdChanged="handleMenuIdChanged">
            </menu-tree>
          </div>
        </Card>
      </Col>
      <Col span="19" style="padding-left: 10px">
        <Row>
          <Col span="24">
            <Card>
              <p slot="title">
                <Icon type="stats-bars"></Icon>
                菜单详情
              </p>
              <a href="#" slot="extra" @click.prevent="handleEdit">
                <Icon type="edit" size="16"></Icon>
              </a>
              <div>
                <menu-content
                  :menuList="menuTreeListForContent"
                  ref="menuContentRef"
                  @refreshDataList="refreshMenuTree"
                  @resourceUpdate="handleResourceUpdated"></menu-content>
              </div>
            </Card>
          </Col>
        </Row>
        <Row style="margin-top: 10px;">
          <Col span="24">
            <Card>
              <p slot="title">
                <Icon type="stats-bars"></Icon>
                关联资源
              </p>
              <Tooltip placement="left" slot="extra">
                <Icon type="information-circled" size="16"></Icon>
                <div slot="content">
                  <p>TODO List</p>
                  <p>
                    <i>1、点击切换列表显示</i>
                  </p>
                  <p>
                    <i>2、可以检索资源，未完成</i>
                  </p>
                </div>
              </Tooltip>
              <div>
                <menu-resource ref="menuResourceRef"
                               @menuResourceChanged="handleMenuResourceChanged"
                               @delete="handleDelete"
                               @resourceUpdate="handleResourceUpdated"></menu-resource>
              </div>
            </Card>
          </Col>
        </Row>
      </Col>
    </Row>
  </div>
</template>

<script>
import menuTree from './components/menu-tree.vue';
import menuContent from './menu-add-or-update.vue';
import menuResource from './components/menu-resource';

export default {
  components: {
    menuTree,
    menuContent,
    menuResource
  },
  data () {
    return {
      /* */
      menuTreeList: [],
      menuTreeListForContent: [
        {
          menuId: 0,
          title: '一级菜单',
          expand: true,
          perms: '',
          url: '',
          type: 0,
          orderNum: 0,
          parentId: -1,
          children: []
        }
      ],
      searchText: '',
      canEdit: false,
      checkedMenuId: -1 // 当前选中的菜单id
    }
  },
  created () {
    this.getMenuTree();
  },
  methods: {
    refreshMenuTree () {
      /* */
      this.$http({
        url: this.$http.adornUrl('/sys/menu/nav'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        if (data && data.code === 0) { // 接口调用成功
          // todo: bugs：由于没有把路由记入vuex中，导致菜单url更新后路由中url没有更新
          // routerUtil.addDynamicMenuRouters(data.menuList); // 添加动态路由
          // router.options.isAddDynamicMenuRoutes = true;
          this.menuTreeList = this.recursiveMenuList(data.menuList);
          this.menuTreeListForContent[0].children = this.recursiveMenuList(data.menuList);
          // 更新状态vuex中的菜单列表
          this.$store.commit('updateMenuList', data.menuList);
          // 更新sessionStorage中的菜单列表和perms
          sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'));
          sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'));
          // 更新资源列表
          // this.$refs.menuResourceRef.getResources(menuNode);
        }
      });
    },
    getMenuTree (searchMenuList) {
      /* 从sesseionStore中获取menuList */
      const menuListInSession = searchMenuList || JSON.parse(sessionStorage.getItem('menuList') || '[]');
      this.menuTreeList = this.recursiveMenuList(menuListInSession);
      // 此处组件复用传值为复杂对象数组，需要值拷贝（浅拷贝），否则复用组件会相互干扰
      this.menuTreeListForContent[0].children = this.recursiveMenuList(menuListInSession);// 错误写法：this.menuTreeList.concat();
    },
    recursiveMenuList (menuList = [], menuTreeData = []) {
      /* 递归menulist构造菜单树结构 */
      menuList.forEach((item, index) => {
        let menu = {};
        menu.menuId = item.menuId;
        menu.title = item.name;
        menu.expand = menuTreeData.length === 0 && index === 0; // 第一个菜单默认展开
        menu.perms = item.perms;
        menu.url = item.url;
        menu.type = item.type;
        menu.orderNum = item.orderNum;
        menu.parentId = item.parentId;
        let child = [];
        if (item.list && item.list.length > 0) {
          this.recursiveMenuList(item.list, child);
        }
        menu.children = child;
        menuTreeData.push(menu);
      });
      return menuTreeData;
    },
    handleAdd () {
      /* 新增菜单 */
      // this.canEdit = false;
      this.reset(true);
      // 设置资源type可编辑
      this.$refs.menuContentRef.handleDisableType(false);
    },
    handleEdit () {
      /* 编辑菜单 */
      if (this.canEdit) {
        this.$refs.menuContentRef.showFormItem(true);
      } else {
        this.$Notice.warning({
          title: '未选中菜单',
          desc: ''
        });
      }
    },
    handleDelete (menuId) {
      /* 删除菜单 */
      if (this.checkedMenuId > 0) {
        /* 删除 */
        this.$Modal.confirm({
          title: '删除操作',
          content: `确定对[id=${this.checkedMenuId}]进行删除操作?`,
          onOk: () => {
            this.$http({
              url: this.$http.adornUrl(`/sys/menu/delete/${menuId || this.checkedMenuId}`),
              method: 'post',
              data: this.$http.adornData()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$Message.success({
                  content: '操作成功',
                  onClose: () => {
                    this.refreshMenuTree();
                    this.checkedMenuId = -2;
                  }
                });
              } else {
                this.$Message.error(data.msg);
              }
            })
          },
          onCancel: () => {
            /* 取消回调 */
          }
        });
      } else {
        this.$Notice.warning({
          title: '未选中菜单',
          desc: ''
        });
      }
    },
    handleSearch () {
      /* 菜单查询 */
      if (this.searchText && /\S/.test(this.searchText)) {
        let searchMenuList = [];
        let menuListInSessionStorage = JSON.parse(sessionStorage.getItem('menuList') || '[]');
        menuListInSessionStorage.forEach(item => {
          /* */
          if (item.name.indexOf(this.searchText) !== -1) {
            searchMenuList.push(item);
          }
        });
        this.getMenuTree(searchMenuList);
      } else {
        this.getMenuTree();
      }
    },
    handleMenuIdChanged (menuNode) {
      /* 接受子组件的传值,调用另外一个子组件的方法，展示/取消展示菜单详情 */
      if (menuNode) { // 选中
        this.canEdit = true;
        this.checkedMenuId = menuNode.menuId;
        this.$nextTick(() => {
          this.$refs.menuContentRef.init(menuNode);
          this.$refs.menuResourceRef.getResources(menuNode);
        });
      } else { // 取消选中
        /* */
        this.canEdit = false;
        this.checkedMenuId = -2;
        /* this.$refs.menuContentRef.resetForm();
        this.$refs.menuResourceRef.clearResourceTag();
        this.$refs.menuContentRef.showFormItem(false); */
        this.reset(false);
      }
    },
    handleResourceUpdated (menuNode) {
      /* 关联资源变更，重新获取子组件内容 */
      this.$refs.menuResourceRef.getResources(menuNode);
    },
    handleMenuResourceChanged (resource) {
      /* 接受子组件menuResource传值，调用兄弟组件的方法，展示菜单关联资源详情 */
      if (resource) {
        this.$refs.menuContentRef.init(resource);
      } else {
        this.$refs.menuContentRef.resetForm();
      }
    },
    reset (isTrue) {
      this.$refs.menuContentRef.resetForm();
      this.$refs.menuResourceRef.clearResourceTag();
      this.$refs.menuContentRef.showFormItem(isTrue);
    }
  }
}
</script>

<style scoped>

</style>
